<?php
/**
 * Created by JetBrains PhpStorm.
 * User: developer2
 * Date: 8/31/12
 * Time: 5:16 PM
 * To change this template use File | Settings | File Templates.
 */
class Db_Accounts_Users extends Common {
	protected static $tableName = TAB_USERS;
	protected static $dbFields = array(
		'id',
		'u_login',
		'u_password',
		'u_email',
		'u_fullname',
		'u_skype',
		'u_group_id',
		'deleted'
	);

	/**
	 * @var Db_Accounts_Users
	 */
	public $objectArray;

	public $id;
	public $u_login;
	public $u_password;
	public $u_email;
	public $u_fullname;
	public $u_skype;
	public $u_group_id;
	public $deleted;

	function __construct($value=NULL, $fieldName=NULL) {
		parent::__construct($value, $fieldName);
	}

	public static function getUsers(){
		$sql = "SELECT `u`.*, `ug`.`ug_name` FROM ?f AS `u`
                LEFT JOIN ?f AS `ug` ON `u`.`u_group_id` = `ug`.`id` WHERE `u`.`deleted` = 0 AND `ug`.`deleted` = 0";
		return self::$DB->select($sql, self::$tableName, TAB_USER_GROUPS);
	}

	public static function getUserById($userId){
		$sql = "SELECT `u`.*, `ug`.`ug_name` FROM ?f AS `u`
                LEFT JOIN ?f AS `ug` ON `u`.`u_group_id` = `ug`.`id` WHERE `u`.`id`=?i AND `u`.`deleted` = 0 AND `ug`.`deleted` = 0";
		return self::$DB->selectRow($sql, self::$tableName, TAB_USER_GROUPS, $userId);
	}

    /**
     * Method getUser are used for verified if User exist , for get user send two param User Name and Password
     *
     * @static
     * @param $name
     * @param $password
     * @return bool|mixed (array)
     */
    public static function getUser($name , $password) {
        if (!empty($name) && !empty($password)) {

            $sql = 'SELECT *, `u`.`id` AS `u_id`, `ug`.`id` AS `ug_id` FROM ?f AS `u`
            INNER JOIN ?f AS `ug` ON `ug`.`id` = `u`.`u_group_id`
            WHERE `u`.`u_login` = ? AND `u`.`u_password` = ? AND `u`.`deleted` = 0 AND `ug`.`deleted` = 0;';

            return self::$DB->selectRow($sql, self::$tableName, TAB_USER_GROUPS, $name, $password);
        } else {
            return false;
        }
    }

	public static function getUsersByGroupName($groupName) {
		$sql = "SELECT `u`.`id`, `u`.`u_login`  FROM ?f AS `u`
				INNER JOIN ?f AS `ug` ON `ug`.`id` = `u`.`u_group_id`
				WHERE `u`.`deleted` = 0 AND `ug`.`deleted` = 0 AND `ug`.`ug_name` = ? ;";
		$usersResult = self::$DB->q($sql, self::$tableName, TAB_USER_GROUPS, $groupName);
		$dataResult = array();
		while($data = $usersResult->fetch_assoc()) {
			$dataResult[$data['id']] = $data['u_login'];
		}
		return $dataResult;
	}

}
